package net.oschina.simpleplus.ctrl;

import java.util.HashMap;
import java.util.Map;

import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import net.oschina.simpleplus.aop.SkipJwtAuth;
import net.oschina.simpleplus.cnf.jwt.JwtCnf;
import net.oschina.simpleplus.entity.User;
import net.oschina.simpleplus.mapper.UserMapper;
import net.oschina.simpleplus.util.B64;
import net.oschina.simpleplus.vm.LoginVm;
import net.oschina.simpleplus.vo.UserVo;

@RestController
public class IndexCtrl {
	
	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private JwtCnf jwtCnf;

	@PostMapping("/login")
	@SkipJwtAuth
	public Map<String, Object> login(@RequestBody LoginVm loginVm){
		User user = userMapper.selectUserByEmail(loginVm.getEmail());
		if(!user.getPasswd().equals(new Md5Hash(loginVm.getPasswd(), loginVm.getEmail()+"_"+ user.getSalt(), 2).toHex())){
			throw new RuntimeException("passwd error!");
		}
		UserVo userVo = new UserVo();
		userVo.setEmail(user.getEmail());
		userVo.setId(user.getId());
		Map<String, Object> m = new HashMap<>();
		m.put("token", jwtCnf.createJwtoken(userVo));
		m.put("user", userVo);
		return m;
	}
	
	@PostMapping("/register")
	@SkipJwtAuth
	public Map<String, Object> register(@RequestBody LoginVm loginVm){
		User user = new User();
		user.setEmail(loginVm.getEmail());
		user.setSalt(B64.getRandomSalt(8));
		user.setPasswd(new Md5Hash(loginVm.getPasswd(), loginVm.getEmail()+"_"+ user.getSalt(), 2).toHex());
		userMapper.saveUser(user);
		return new HashMap<>();
	}
	
	@GetMapping("/getUserInfo")
	public Map<String, Object> getUserInfo(UserVo userVo){
		Map<String, Object> m = new HashMap<>();
		m.put("user", userVo);
		return m;
	}
}
